package gyb.rasa.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import gyb.rasa.common.handler.exceptionhandler.MyException;
import gyb.rasa.common.utils.IPUtils;
import gyb.rasa.common.utils.JwtUtil;
import gyb.rasa.entity.Ip;
import gyb.rasa.entity.RasaMsg;
import gyb.rasa.entity.vo.HotQuestion;
import gyb.rasa.mapper.MessageReceivedMapper;
import gyb.rasa.service.HotService;
import gyb.rasa.service.IpService;
import gyb.rasa.service.MessageReceivedService;
import gyb.rasa.entity.MessageReceived;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郜宇博
 * @since 2023-04-02
 */
@Service
public class MessageReceivedServiceImpl extends ServiceImpl<MessageReceivedMapper, MessageReceived> implements MessageReceivedService {


    private final HotService hotService;
    private final IpService ipService;

    public MessageReceivedServiceImpl(HotService hotService, IpService ipService) {
        this.hotService = hotService;
        this.ipService = ipService;
    }

    @Override
    public int addChat(RasaMsg rasaMsg, HttpServletRequest request, ArrayList<Map<String,String>> response) {
        //获取时间
        String when = DateUtil.now();
        //System.out.println("when:"+when);
        //获取ip
        String ipAdress = IPUtils.getIpAddr(request);
        //获取sessionId
        String sessionId = UUID.randomUUID().toString().replaceAll("-","");
        MessageReceived messageReceived = new MessageReceived();
        messageReceived.setMid(null);
        messageReceived.setFromUserId(rasaMsg.getSender());
        messageReceived.setSessionId(sessionId);
        messageReceived.setContent(rasaMsg.getMessage());
        messageReceived.setWhen(when);
        messageReceived.setIpAddress(ipAdress);
        ArrayList<String> res = new ArrayList<>();
        String entity = null;
        for (Map<String, String> map : response) {
            if (map.containsKey("buttons")){
                res.add(map.get("buttons"));
            }
            if (map.containsKey("text")){
                res.add(map.get("text"));
            }
            if (map.containsKey("attachment")){
                entity = map.get("attachment");
            }

        }
        messageReceived.setEntity(entity);
        String responseStr = JSONUtil.toJsonStr(res);
        messageReceived.setResponse(responseStr);
        baseMapper.insert(messageReceived);
        //存入ip到ip表
        ipService.addIpUnique(ipAdress);
        return messageReceived.getMid();
    }

    /**
     * 获取HotQuestion格式的问答
     * @param mid message_receive主键
     * @return HotQuestion格式的question
     */
    @Override
    public HotQuestion getMessageReceiveTransformHotQuestion(Integer mid) {
        MessageReceived messageReceived = baseMapper.selectById(mid);
        //转换为HotQuestion
        HotQuestion question = hotService.transformToHotQes(messageReceived);
        //将时间更改为具体时间
        question.setWhen(messageReceived.getWhen());
        return question;
    }

    /**
     * 获取最佳回复
     *
     * @return HotQuestionList
     */
    @Override
    public List<HotQuestion> getGoodResponses(Integer count) {
        QueryWrapper<MessageReceived> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("good").last("limit "+count);
        List<MessageReceived> messageReceiveds = baseMapper.selectList(queryWrapper);
        //结果集
        List<HotQuestion> result = new ArrayList<>();
        for (MessageReceived messageReceived : messageReceiveds) {
            HotQuestion question = hotService.transformToHotQes(messageReceived);
            result.add(question);
        }
        return result;
    }

    /**
     * 获取messages页码格式
     *
     * @param current 页数
     * @param limit 每页大小
     * @return
     */
    @Override
    public IPage<MessageReceived> getMessageListByPage(Long current, Long limit,Integer good) {
        Page<MessageReceived> page = new Page<>(current, limit);
        QueryWrapper<MessageReceived> queryWrapper = new QueryWrapper<MessageReceived>().orderByDesc("mid");
        if (good == 1){
            queryWrapper = new QueryWrapper<MessageReceived>().orderByDesc("good");
        }
        IPage<MessageReceived> messageList = this.page(page,queryWrapper);
        return messageList;
    }

    /**
     * 分页通过uid获取message
     *
     * @param uid 用户id
     * @return messageList
     */
    @Override
    public IPage<MessageReceived> getMessageByUid(Long current, Long limit, Integer uid, HttpServletRequest httpServletRequest) {
        //是否同一用户
        String uidStr = JwtUtil.getMemberIdByJwtToken(httpServletRequest);
        if (uid != Integer.parseInt(uidStr)){
            throw new MyException(20001,"没有权限获取其他用户信息");
        }
        Page<MessageReceived> page = new Page<>(current, limit);
        QueryWrapper<MessageReceived> queryWrapper = new QueryWrapper<MessageReceived>().eq("from_user_id", uid).orderByDesc("`when`");
        IPage<MessageReceived> messageList = this.page(page, queryWrapper);
        return messageList;
    }
}
